package io.zcoder.innoway.fragments;


import android.Manifest;
import android.animation.Animator;
import android.app.Activity;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.clj.fastble.BleManager;
import com.clj.fastble.conn.BleCharacterCallback;
import com.clj.fastble.conn.BleGattCallback;
import com.clj.fastble.data.ScanResult;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.scan.ListScanCallback;
import com.clj.fastble.utils.HexUtil;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.MultiplePermissionsReport;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.multi.MultiplePermissionsListener;
import com.karumi.dexter.listener.single.PermissionListener;
import com.squareup.picasso.Picasso;

import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import io.zcoder.innoway.R;
import io.zcoder.innoway.models.ResponseBase;
import io.zcoder.innoway.utils.Utils;
import io.zcoder.innoway.activities.EntryDetailActivity;
import io.zcoder.innoway.activities.FamilyMembersActivity;
import io.zcoder.innoway.activities.ManualEntryActivity;
import io.zcoder.innoway.commons.Constants;
import io.zcoder.innoway.commons.PrefUtils;
import io.zcoder.innoway.models.Dashboard;
import io.zcoder.innoway.models.DashboardResponse;
import io.zcoder.innoway.models.Profile;
import io.zcoder.innoway.models.ProfileDetailResponse;
import io.zcoder.innoway.rest.RestClient;
import io.zcoder.innoway.widgets.TextViewCustom;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

import static android.app.Activity.RESULT_OK;

public class DashboardFragment extends BaseFragment {

    public static final int REQUEST_ADD_ENTRY = 123;
    public static final int REQUEST_FAMILY = 124;

    //    public static final String DEVICE_NAME = "BT-163";
    public static final String DEVICE_NAME = "eBody-Fat-Scale";
    public static final String UUID_SERVICE = "fff0";
    public static final String UUID_NOTIFY = "fff4";
    public static final String UUID_WRITE = "fff3";
    public String UUID_SERVICE_FOR_CURRENT = null;
    public String UUID_NOTIFY_FOR_CURRENT = null;
    public String UUID_WRITE_FOR_CURRENT = null;
    public static final long TIME_OUT = 5 * 60 * 1000;

    @BindView(R.id.clock_weight)
    ImageView mClockWeight;
    @BindView(R.id.pointer)
    ImageView mPointer;
    @BindView(R.id.common_add)
    ImageView mAdd;
    @BindView(R.id.common_avatar)
    CircleImageView mAvatar;
    @BindView(R.id.btn_connect)
    TextViewCustom mBtnConnect;
    @BindView(R.id.goal_text)
    TextViewCustom mYourWeight;
    @BindView(R.id.weight_text)
    TextViewCustom mWeighClock;
    @BindView(R.id.to_go_text)
    TextViewCustom mToGoText;
    @BindView(R.id.date_text)
    TextViewCustom mDate;
    @BindView(R.id.bmi)
    TextViewCustom mBmi;
    @BindView(R.id.body_fat)
    TextViewCustom mBodyFat;
    @BindView(R.id.muscle)
    TextViewCustom mMuscle;
    @BindView(R.id.water)
    TextViewCustom mWater;
    @BindView(R.id.visceral_fat)
    TextViewCustom mVisceralFat;
    @BindView(R.id.bone_mass)
    TextViewCustom mBoneMass;
    @BindView(R.id.bmr)
    TextViewCustom mBmr;

    //testing
    @BindView(R.id.logtv)
    TextView logtv;

    @OnClick(R.id.btn_connect)
    void connect() {
        checkAndScan();
    }

    Dashboard mEntry;

    @OnClick(R.id.layout_bmi)
    void openDetail0() {
        onDetail(0);
    }

    @OnClick(R.id.layout_body_fat)
    void openDetail1() {
        onDetail(1);
    }

    @OnClick(R.id.layout_muscle)
    void openDetail2() {
        onDetail(2);
    }

    @OnClick(R.id.layout_water)
    void openDetail3() {
        onDetail(3);
    }

    @OnClick(R.id.layout_bone_mass)
    void openDetail6() {
        onDetail(4);
    }

    @OnClick(R.id.layout_bmr)
    void openDetail7() {
        onDetail(5);
    }

    @OnClick(R.id.layout_visceral_fat)
    void openDetail5() {
        onDetail(6);
    }

    @OnClick(R.id.common_avatar)
    void openProfiles() {
        Intent intent = new Intent(getActivity(), FamilyMembersActivity.class);
        startActivityForResult(intent, REQUEST_FAMILY);
    }

    @OnClick(R.id.common_add)
    void add() {
        Intent intent = new Intent(getActivity(), ManualEntryActivity.class);
        if (mDashboard != null) {
            intent.putExtra(Constants.DASHBOARD_EXTRAS, mDashboard);
        }
        if (mProfile != null) {
            intent.putExtra(Constants.WEIGHT_TYPE_EXTRAS, mProfile.getWeight_unit());
        }
        startActivityForResult(intent, REQUEST_ADD_ENTRY);
    }

    private Dashboard mDashboard;
    private Profile mProfile;
    BleManager bleManager;

    float lastweight;
    float lastfat;
    float lastvisfat;
    float lastmuscle;
    float lastwater;
    float lastbmi;
    float lastbmr;
    float lastbone;
    float lastheight;
    boolean isSetNotify = false;

    private Activity mActivity;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.layout_dashboard_fragment, container, false);
        setTitle(getString(R.string.dashboard));
        ButterKnife.bind(this, view);
        mAvatar.setVisibility(View.VISIBLE);
        mAdd.setVisibility(View.VISIBLE);
        mActivity = getActivity();
        mPointer.setRotation(-135);
        getProfile();
        mEntry = new Dashboard();
        bleManager = new BleManager(getActivity());
        bleManager.enableBluetooth();
        checkAndScan();
        return view;
    }

    private void checkAndScan() {
        if (bleManager.isConnectingOrConnected() || bleManager.isInScanning()) {
            return;
        }

        Dexter.withActivity(mActivity)
                .withPermissions(
                        Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE
                ).withListener(new MultiplePermissionsListener() {
            public void onPermissionsChecked(MultiplePermissionsReport report) {
                scan();
            }

            public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions,
                                                           PermissionToken token) {
            }
        }).check();
    }

    private boolean isMainThread() {
        return Looper.getMainLooper().getThread() == Thread.currentThread();
    }

    private void logBle(String log) {
        Log.d("BLE", log);
        String text = logtv.getText().toString();
        if (text == null || text.length() <= 0) {
            text = log;
        } else {
            text += "\n" + log;
        }
        logtv.setText(text);
    }

    private void cleanBle() {
        if (bleManager.isInScanning()) {
            bleManager.cancelScan();
        }
        bleManager.closeBluetoothGatt();

        mBtnConnect.setText(getString(R.string.not_connect));
        UUID_SERVICE_FOR_CURRENT = null;
        UUID_NOTIFY_FOR_CURRENT = null;
        UUID_WRITE_FOR_CURRENT = null;

        lastweight = 0;
        lastfat = 0;
        lastvisfat = 0;
        lastmuscle = 0;
        lastwater = 0;
        lastbmi = 0;
        lastbmr = 0;
        lastbone = 0;
        lastheight = 0;
        isSetNotify = false;
        mBtnConnect.postDelayed(new Runnable() {
            public void run() {
                scan();
            }
        }, 1000);
    }

    private void scan() {
        logBle("Begin scan" + ", isInMainThread>>" + isMainThread());
        mBtnConnect.setText(getString(R.string.connecting));
        bleManager.scanDevice(new ListScanCallback(TIME_OUT) {
            public void onScanning(final ScanResult result) {
                getActivity().runOnUiThread(new Runnable() {
                    public void run() {
                        logBle("Device found>>" + "NAME: " + result.getDevice().getName() + " MAC:" + result.getDevice().getAddress());
                        //Log.d("BLE", "NAME: " + result.getDevice().getName() + " MAC:" + result.getDevice().getAddress());
                        if (DEVICE_NAME.equals(result.getDevice().getName())) {
                            connectDevice(result);
                        }
                    }
                });
            }

            public void onScanComplete(ScanResult[] results) {
                getActivity().runOnUiThread(new Runnable() {
                    public void run() {
                        logBle("scan complete");
                        if (!bleManager.isConnectingOrConnected()) {
                            cleanBle();
                        }
                    }
                });
            }
        });
    }

    private void connectDevice(ScanResult result) {
        logBle("connectDevice...");
        bleManager.connectDevice(result, true, new BleGattCallback() {
            public void onConnectError(BleException exception) {
                Log.d("BLE", "connectDevice>>onConnectError" + ", isInMainThread>>" + isMainThread());
                getActivity().runOnUiThread(new Runnable() {
                    public void run() {
                        logBle("onConnectError");
                        cleanBle();
                    }
                });
            }

            public void onConnectSuccess(final BluetoothGatt gatt, int status) {
                Log.d("BLE", "connectDevice>>onConnectSuccess" + ", isInMainThread>>" + isMainThread());
                getActivity().runOnUiThread(new Runnable() {
                    public void run() {
                        logBle("onConnectSuccess");
                        logBle("discoverServices");
                        gatt.discoverServices();
                    }
                });
            }

            public void onDisConnected(BluetoothGatt gatt, int status, BleException exception) {
                Log.d("BLE", "connectDevice>>onDisConnected" + ", isInMainThread>>" + isMainThread());
                getActivity().runOnUiThread(new Runnable() {
                    public void run() {
                        logBle("onDisConnected");
                        cleanBle();
                    }
                });
            }

            public void onServicesDiscovered(final BluetoothGatt gatt, int status) {
                Log.d("BLE", "connectDevice>>onServicesDiscovered" + ", isInMainThread>>" + isMainThread());
                getActivity().runOnUiThread(new Runnable() {
                    public void run() {
                        if (gatt.getServices() == null) {//no services
                            logBle("device no services");
                            cleanBle();
                        } else {
                            //find
                            BluetoothGattService n_gattService = null;
                            for (BluetoothGattService gattService : gatt.getServices()) {
                                String uuid = gattService.getUuid().toString();
                                logBle("SERVICE ID: " + uuid);
                                if (uuid != null && uuid.contains(UUID_SERVICE)) {
                                    n_gattService = gattService;
                                    UUID_SERVICE_FOR_CURRENT = uuid;
                                    break;
                                }
                            }

                            if (n_gattService != null) {
                                logBle("Service found");
                                boolean bfindNotify = false;
                                boolean bfindWrite = false;
                                for (BluetoothGattCharacteristic c : n_gattService.getCharacteristics()) {
                                    logBle("Characteristic: " + c.getUuid());
                                    if (c.getUuid().toString().contains(UUID_NOTIFY)) {
                                        UUID_NOTIFY_FOR_CURRENT = c.getUuid().toString();
                                        bfindNotify = true;
                                    } else if (c.getUuid().toString().contains(UUID_WRITE)) {
                                        UUID_WRITE_FOR_CURRENT = c.getUuid().toString();
                                        bfindWrite = true;
                                    }
                                }
                                if (bfindNotify && bfindWrite) {
                                    mBtnConnect.setText(getString(R.string.connected));
                                    logBle("set notify");
                                    mBtnConnect.postDelayed(new Runnable() {
                                        public void run() {
                                            goNotify();
                                        }
                                    }, 2);
                                } else {
                                    logBle("Characteristic not exist");
                                    cleanBle();
                                }
                            } else {
                                logBle("device services not exist");
                                cleanBle();
                            }
                        }
                    }
                });
            }
        });
    }

    private void goNotify() {
        if (UUID_SERVICE_FOR_CURRENT == null || UUID_NOTIFY_FOR_CURRENT == null)
            return;

        bleManager.notify(
                UUID_SERVICE_FOR_CURRENT,
                UUID_NOTIFY_FOR_CURRENT,
                new BleCharacterCallback() {
                    public void onSuccess(final BluetoothGattCharacteristic characteristic) {
                        Log.d("BLE", "goNotify>>onSuccess" + ", isInMainThread>>" + isMainThread());
                        getActivity().runOnUiThread(new Runnable() {
                            public void run() {
                                logBle("Received BYTE(notify callback):" + Utils.byteArraytoHex(characteristic.getValue()));
                                logBle("notify success");
                                processByte(characteristic.getValue());
                                if (!isSetNotify) {
                                    logBle("goto write");
                                    mBtnConnect.postDelayed(new Runnable() {
                                        public void run() {
                                            goWrite();
                                        }
                                    }, 2);
                                }
                                isSetNotify = true;
                            }
                        });
                    }

                    public void onFailure(final BleException exception) {
                        Log.d("BLE", "goNotify>>onFailure" + ", isInMainThread>>" + isMainThread());
                        getActivity().runOnUiThread(new Runnable() {
                            public void run() {
                                showSnackBar(exception.getDescription());
                                logBle("notify failed");
                                cleanBle();
                            }
                        });
                    }

                    public void onInitiatedResult(final boolean result) {
                        Log.d("BLE", "goNotify>>onInitiatedResult" + ", isInMainThread>>" + isMainThread());
                        getActivity().runOnUiThread(new Runnable() {
                            public void run() {
                                logBle("notify init >>" + result);
                            }
                        });
                    }
                });
    }

    private void goWrite() {
        if (UUID_SERVICE_FOR_CURRENT == null || UUID_WRITE_FOR_CURRENT == null)
            return;

        byte weighthigh, weightlow, sportlvl = '\0', genderage, height;
        double weight = mDashboard.getWeight();
        if (weight == 0) {
            weight = mProfile.getInitWeight();
        }
        weighthigh = (byte) (((int) (weight * 10)) / 256);
        weightlow = (byte) (((int) (weight * 10)) % 256);
        weighthigh += 64;

        String sportlvlstr = mProfile.getProfession();
        //User number of the scale
        sportlvl = 0;

        sportlvl += 0x00;//Scales
        if (sportlvlstr == null || sportlvlstr.isEmpty()) {
            sportlvl += 0;
        } else {
            //Service network is 0,1,2 grade equipment is now 0,1,2 level
            sportlvl += mProfile.getProfessionInt() * 0x10;
        }
        sportlvl += 0;//User zero


        Calendar today = Calendar.getInstance();
        Date birdDate = Utils.convertToDate(mProfile.getBirthday(), Utils.DATE_FORMAT_FULL);
        Calendar birdCalendar = Calendar.getInstance();
        birdCalendar.setTime(birdDate);
        int age = today.get(Calendar.YEAR) - birdCalendar.get(Calendar.YEAR);
        if (mProfile.getGender() == 1) {
            genderage = (byte) (age + 128);
        } else {
            genderage = (byte) age;
        }

        height = (byte) mProfile.getHeight();
        byte setUserInfo[] = {(byte) 0xfd, (byte) 0x53, weighthigh, weightlow, sportlvl, genderage, height};

        bleManager.writeDevice(
                UUID_SERVICE_FOR_CURRENT,
                UUID_WRITE_FOR_CURRENT,
                setUserInfo,
                new BleCharacterCallback() {
                    public void onSuccess(final BluetoothGattCharacteristic characteristic) {
                        Log.d("BLE", "goWrite>>onSuccess" + ", isInMainThread>>" + isMainThread());
                        getActivity().runOnUiThread(new Runnable() {
                            public void run() {
                                logBle("write success");
                                logBle("Received BYTE(write callback):" + Utils.byteArraytoHex(characteristic.getValue()));
//                        byte values[] = characteristic.getValue();
//                        Log.d("Received BYTE", Utils.byteArraytoHex(values));
//                        processByte(values);
                                //logBle("wait >> receive device data");
                            }
                        });
                    }

                    public void onFailure(final BleException exception) {
                        Log.d("BLE", "goWrite>>onFailure" + ", isInMainThread>>" + isMainThread());
                        getActivity().runOnUiThread(new Runnable() {
                            public void run() {
                                showSnackBar(exception.getDescription());
                                logBle("write failed");
                                cleanBle();
                            }
                        });
                    }

                    public void onInitiatedResult(final boolean result) {
                        Log.d("BLE", "goWrite>>onInitiatedResult" + ", isInMainThread>>" + isMainThread());
                        getActivity().runOnUiThread(new Runnable() {
                            public void run() {
                                logBle("write init >>" + result);
                            }
                        });
                    }
                });
    }

    private void processByte(byte[] bytes) {
        logBle("processByte");
        if (bytes == null || bytes.length <= 0)
            return;

        if (bytes[0] == (byte) 0x00 && bytes.length == 3) {
            byte weightHigh = (byte) ((bytes[1] & 0xff) & (byte) 0x3F);
            float weightdata = (float) (weightHigh * 256 + (bytes[2] & 0xff)) / 10.0f;
            if (((bytes[1] & 0xff) & 0x3f) * 256 + (bytes[2] & 0xff) == 0x3f * 256 + 255) {
                logBle("Data weight error");
            } else {
                mEntry.setWeight(weightdata);
            }
        }

        if ((bytes[0] == (byte) 0xff) && bytes.length == 20) {
            Byte weightHigh = (byte) ((bytes[1] & 0xff) & (byte) 0x3f);
            float weightdata = (float) (weightHigh * 256 + (bytes[2] & 0xff)) / 10.0f;
            float heightdata = (bytes[10] & 0xff) / 100.0f;
            float fatdata = ((bytes[12] & 0xff >> 4) * 256 + bytes[11] & 0xff) / 10.0f;
            float waterdata = ((bytes[12] & 0xff & 0x0f) * 256 + bytes[13] & 0xff) / 10.0f;
            float muscledata = (bytes[14] & 0xff * 256 + bytes[15] & 0xff) / 10.0f;
            float bonedata = (bytes[16] & 0xff) / 10.0f;
            int visfatdata = bytes[17] & 0xff;
            int bmrdata = bytes[18] & 0xff * 256 + bytes[19] & 0xff;
            float bmidata = weightdata / (heightdata * heightdata);

            // do stuff
            if (!(weightdata == lastweight && fatdata == lastfat && waterdata == lastwater
                    && bonedata == lastbone && bmidata == lastbmi && bmrdata == lastbmr
                    && heightdata == lastheight && muscledata == lastmuscle && visfatdata == lastvisfat)) {

                //[RCCircleAnimation stopAnimation:_circleImageView.layer];

                lastweight = weightdata;
                lastfat = fatdata;
                lastwater = waterdata;
                lastbone = bonedata;
                lastbmi = bmidata;
                lastbmr = bmrdata;
                lastheight = heightdata;
                lastmuscle = muscledata;
                lastvisfat = visfatdata;

                if ((bytes[12] >> 4) == 0x0f ||
                        fatdata >= 100 ||
                        waterdata >= 100)    //The measurement results are wrong
                {
                    showSnackBar("Measurement error! Please check the personal information and measurement process!");

                } else if (((bytes[1] & 0xff) & 0x3f) * 256 + (bytes[2] & 0xff) == 0x3f * 256 + 255) {
                    Log.e("BLE", "OL");
                } else//The measurement results are correct
                {
                    mEntry.setWeight(weightdata);
                    mEntry.setBody_fat(fatdata);
                    mEntry.setWater(waterdata);
                    mEntry.setMuscle(muscledata);
                    mEntry.setVisceral_fat(visfatdata);
                    mEntry.setBmr(bmrdata);
                    mEntry.setBmi(bmidata);
                    mEntry.setBone_mass(bonedata);
                    submitDashboard();
                    mBtnConnect.postDelayed(new Runnable() {
                        public void run() {
                            goWriteOk();
                        }
                    }, 2);
                }
            }
        }

        try {
            String result = new String(bytes, "UTF-8");
            if (result.equals("EOM")) {
                logBle("EOM and restart");
                cleanBle();
            }
        } catch (UnsupportedEncodingException e) {
            logBle("Byte[] UnsupportedEncodingException");
        }
    }

    void goWriteOk() {
        if (UUID_SERVICE_FOR_CURRENT == null || UUID_WRITE_FOR_CURRENT == null)
            return;

        logBle("goto WriteOk");
        byte getData[] = {(byte) 0xfd, (byte) 0x30};
        bleManager.writeDevice(
                UUID_SERVICE_FOR_CURRENT,
                UUID_WRITE_FOR_CURRENT,
                getData,
                new BleCharacterCallback() {
                    public void onSuccess(final BluetoothGattCharacteristic characteristic) {
                        Log.d("BLE", "goWriteOk>>onSuccess" + ", isInMainThread>>" + isMainThread());
                        getActivity().runOnUiThread(new Runnable() {
                            public void run() {
                                //byte values[] = characteristic.getValue();
                                logBle("goWriteOk>>write success");
                                logBle("goWriteOk>>Received BYTE(write callback):" + Utils.byteArraytoHex(characteristic.getValue()));
                            }
                        });
                    }

                    public void onFailure(BleException exception) {
                        Log.d("BLE", "goWriteOk>>onFailure" + ", isInMainThread>>" + isMainThread());
                        getActivity().runOnUiThread(new Runnable() {
                            public void run() {
                                logBle("goWriteOk>>onFailure");
                                cleanBle();
                            }
                        });
                    }

                    public void onInitiatedResult(final boolean result) {
                        Log.d("BLE", "goWriteOk>>onInitiatedResult" + ", isInMainThread>>" + isMainThread());
                        getActivity().runOnUiThread(new Runnable() {
                            public void run() {
                                logBle("goWriteOk>>write init >>" + result);
                            }
                        });
                    }
                });
    }

    void submitDashboard() {
        showProgress();
        if (mEntry != null && mProfile != null) {
            mEntry.setId(mProfile.getId());
        }
        RestClient.build(getActivity(), true).addEntry(mEntry, new Callback<ResponseBase>() {
            @Override
            public void success(ResponseBase responseBase, Response response) {
                hideProgress();
                if (responseBase.getStatus_code() != 200) {
                    showAlert(getString(R.string.error), responseBase.getMessage());
                } else {
                    getDashboard();
                }
            }

            @Override
            public void failure(RetrofitError error) {
                hideProgress();
            }
        });
//        saveGoogleFit(mDashboard);
    }


    public void showSnackBar(String string) {
        Snackbar.make(getActivity().findViewById(android.R.id.content), string, Snackbar.LENGTH_SHORT).show();
    }

    private void getProfile() {
        RestClient.build(getActivity(), true).getProfile(PrefUtils.getInt(getActivity(), PrefUtils.PREF_PROFILE_ID),
                new Callback<ProfileDetailResponse>() {
                    @Override
                    public void success(ProfileDetailResponse profileDetailResponse, Response response) {
                        if (profileDetailResponse.getStatus_code() != 200) {
                            showAlert(getString(R.string.error), profileDetailResponse.getMessage());
                        } else if (profileDetailResponse.getData() != null) {
                            mProfile = profileDetailResponse.getData();
                            setTitle(mProfile.getFirst_name() + " " + mProfile.getLast_name());
                            if (!Utils.isBlank(mProfile.getAvatar_url())) {
                                Picasso.with(mActivity).load(mProfile.getAvatar_url()).into(mAvatar);
                            } else {
                                mAvatar.setImageResource(0);
                            }
                            getDashboard();
                        }

                    }

                    @Override
                    public void failure(RetrofitError error) {
                    }
                });
    }

    private void getDashboard() {
        if (mProfile != null) {
            RestClient.build(getActivity(), true).getDashboard(PrefUtils.getInt(getActivity(), PrefUtils.PREF_PROFILE_ID),
                    new Callback<DashboardResponse>() {
                        @Override
                        public void success(DashboardResponse dashboardResponse, Response response) {
                            hideProgress();
                            if (dashboardResponse.getStatus_code() != 200) {
                                showAlert(getString(R.string.error), dashboardResponse.getMessage());
                            } else if (dashboardResponse.getData() != null) {
                                mDashboard = dashboardResponse.getData();
                                fillData();
                            }

                        }

                        @Override
                        public void failure(RetrofitError error) {
                            hideProgress();
                        }
                    });
        }
    }

    private void fillData() {
        if (mProfile.getWeight_unit() == 1) {
            mClockWeight.setImageResource(R.drawable.weight_meter_lb);
            mPointer.setRotation(-135);
            mPointer.animate().setDuration(500).rotation(mDashboard.getWeight(mProfile.getWeight_unit()) * 9 / 8 - 135);
        } else {
            mClockWeight.setImageResource(R.drawable.weight_meter_kg);
            mPointer.setRotation(-135);
            mPointer.animate().setDuration(500).rotation((mDashboard.getWeight(mProfile.getWeight_unit()) * 9 / 4 - 135));
        }

        mWeighClock.setText(mDashboard.getWeightWithUnit(mProfile.getWeight_unit()));
        ///*mDashboard.getWeight(mProfile.getWeight_unit()) + "\n" + Utils.getUnitWeight(mProfile.getWeight_unit())*/
        mYourWeight.setText(mProfile.getGoalWeightWithUnit(mProfile.getWeight_unit()));
        mToGoText.setText(String.format("%.1f\n" + Utils.getUnitWeight(mProfile.getWeight_unit()), Math.abs(mProfile.getGoalWeight(mProfile.getWeight_unit()) - mDashboard.getWeight(mProfile.getWeight_unit()))));

        String percent = getString(R.string.percent);
        mBmi.setText(mDashboard.getBmi() + "");
        mBodyFat.setText(String.format(percent, mDashboard.getBody_fat() + ""));
        mMuscle.setText(String.format(percent, mDashboard.getMuscle() + ""));
        mWater.setText(String.format(percent, mDashboard.getWater() + ""));
        mVisceralFat.setText(String.format(percent, mDashboard.getVisceral_fat() + ""));
        mBoneMass.setText(String.format("%sKg", mDashboard.getBone_mass() + ""));
        mBmr.setText(String.format("%sKcal", mDashboard.getBmr() + ""));
        if (!Utils.isBlank(mDashboard.getSaved_time())) {
            mDate.setText(Utils.convertToString(Utils.convertToDate(mDashboard.getSaved_time(),
                    Utils.DATE_FORMAT_FULL), Utils.DATE_FORMAT_MMM_DD_YYYY));
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if ((requestCode == REQUEST_ADD_ENTRY || requestCode == REQUEST_FAMILY) && resultCode == RESULT_OK) {
            getProfile();
        }
    }

    void onDetail(int index) {
        if (mDashboard != null) {
            Intent intent = new Intent(getActivity(), EntryDetailActivity.class);
            intent.putExtra(Constants.DASHBOARD_EXTRAS, mDashboard);
            intent.putExtra(Constants.INDEX_EXTRAS, index);
            startActivity(intent);
        }
    }
}
